package fantasy;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.Iterator;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class CronUpdateXmlServlet extends HttpServlet {
	

	/**
	 * 
	 */
	private static final long serialVersionUID = -7463931188967846547L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		// Initiate Persistence Manager for Yahoo OAuth information
		PersistenceManager pm = PMF.get().getPersistenceManager();
        
		// Stuff to get baseurl
		Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("fantasy.properties"));
        String baseurl = props.getProperty("application.baseurl");

		String api_url = "http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=mlb/leagues;out=settings,standings";
        YahooApiQuery yahoo = new YahooApiQuery();
        
        Query query = pm.newQuery(UserTable.class);
        
        try {
            List<UserTable> results = (List<UserTable>) query.execute();
            if(results.iterator().hasNext()) {
            	for(UserTable u : results) {
            		yahoo.setUser(u.getUserkey());
            		String xml = yahoo.query(api_url);
            		saveLeagueXml(u.getUserkey(), xml);
            	}
            }
        } finally {
        	query.closeAll();
        }

			
		
		
        
	}
	
	private void saveLeagueXml(final String user_nickname, final String xml_as_string) {
		
		LeagueXml l = new LeagueXml();
		l.setUserkey(user_nickname);
		l.setLeaguexml(xml_as_string);
		
		PersistenceManager pm2 = PMF.get().getPersistenceManager();
		try {
			pm2.makePersistent(l);
		} finally {
			pm2.close();
		}
	}
	

}
